<template>
  <a-flex gap="middle" style="height: 100%">
    <a-card title="WebSocket 在线测试" style="height: 100%; display: flex; flex-direction: column">
      <a-flex vertical gap="small" style="height: 100%">
        <a-flex gap="small">
          <a-input v-model:value="webSocketUrl" style="width: 300px"></a-input>
          <a-button
            type="primary"
            :disabled="!webSocketUrl || websocketStatus"
            @click="openWebsocket"
            >连接</a-button
          >
          <a-button type="primary" @click="closeWebsocket" :disabled="!websocketStatus" danger
            >断开</a-button
          >
        </a-flex>
        <a-flex vertical gap="small">
          <label class="tipStyle"
            >1.连接格式为 ws://IP或域名:端口（示例ws://124.222.6.60:8800）</label
          >
          <label class="tipStyle">2.对于内网的测试环境，只需填入服务端的内网IP和端口</label>
          <label class="tipStyle">3.可连接我上面提供的服务端ws地址来测试您自己的客户端</label>
        </a-flex>
        <a-flex flex="1" vertical gap="middle">
          <a-textarea
            defaultValue="消息内容，ctrl+enter换行"
            v-model:value="websocketContent"
            style="height: 100%; resize: none"
            @pressEnter="handleEnterPress"
            ref="textareaRef"
          ></a-textarea>
          <a-button
            type="primary"
            style="width: 100%"
            :disabled="!webSocketUrl"
            @click="sendWebsocketMsg"
          >
            发送(回车)
          </a-button>
        </a-flex>
      </a-flex>
    </a-card>
    <a-flex flex="1">
      <a-card style="width: 100%">
        <div
          ref="messageContainer"
          style="width: 100%; overflow-y: auto"
          :style="{ height: containerHeight + 'px' }"
        >
          <a-flex vertical gap="small">
            <template v-for="(msg, index) in websocketMsgs" :key="index">
              <a-flex vertical>
                <a-flex gap="small" :class="msg.type">
                  <label>{{ msg.type }}</label>
                  <label>{{ msg.time }}</label>
                </a-flex>
                <div class="msgContentShow">{{ msg.content }}</div>
              </a-flex>
            </template>
          </a-flex>
        </div>
      </a-card>
    </a-flex>
  </a-flex>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

const webSocketUrl = ref('ws://124.222.6.60:8800')
const websocketMsgs = ref([])
const websocketContent = ref('')
const containerHeight = ref(0)
const websocketStatus = ref(false)
const messageContainer = ref(null)
const textareaRef = ref(null)

// 打开 WebSocket 连接
const openWebsocket = () => {
  window.api.openWebsocket(webSocketUrl.value)
  websocketStatus.value = true
}

// 关闭 WebSocket 连接
const closeWebsocket = () => {
  window.api.closeWebsocket()
  websocketStatus.value = false
}

// 处理 enter 键按下事件
const handleEnterPress = (event) => {
  if (event.ctrlKey) {
    websocketContent.value += '\n'
  } else {
    event.preventDefault()
    sendWebsocketMsg()
  }
}

// 发送 WebSocket 消息
const sendWebsocketMsg = () => {
  if (websocketContent.value) {
    console.log(websocketContent.value)
    window.api.sendWebsocketMsg(websocketContent.value)
    websocketContent.value = ''
    textareaRef.value.focus()
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value.scrollHeight) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

window.electron.ipcRenderer.on('socket-msg-from-main', (event, message) => {
  websocketMsgs.value.push(message)
  scrollToBottom()
})

const calculateContainerHeight = () => {
  containerHeight.value
  setTimeout(() => {
    const cardElement = document.querySelector('.ant-card')
    if (cardElement) {
      containerHeight.value = cardElement.offsetHeight - 60
    }
  }, 50)
}

onMounted(() => {
  calculateContainerHeight()
  window.addEventListener('resize', calculateContainerHeight)
  window.api.getWebsocketStatus().then((result) => {
    console.log("获取到socket状态", result)
    websocketStatus.value = result
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', calculateContainerHeight)
})
</script>

<style scoped>
.tipStyle {
  color: #888888;
  font-size: 14px;
  line-height: 1.5;
}

.ant-card :deep(.ant-card-body) {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

/* 消息样式 */
.send {
  color: #008000;
  font-weight: bold;
}

.receive {
  color: #0000ff;
  font-weight: bold;
}

.system {
  color: #808080;
  font-style: italic;
}

.msgContentShow {
  white-space: pre-wrap;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
  margin-top: 4px;
  margin-right: 10px;
  word-break: break-word;
}

/* 添加滚动条样式 */
div[style*='overflow-y: auto']::-webkit-scrollbar {
  width: 8px;
}

div[style*='overflow-y: auto']::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

div[style*='overflow-y: auto']::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
